# -*- coding: utf-8 -*-
from pipe import Pipe
import threading
from req import  Req
import Util#Util.getDict
import random
from factoryReq import  ReqFactory
from mongoBase import MongoDBBase
from factoryFetcher import Fetcher
import units
from factoryUnit import UnitFactory
class Saver(threading.Thread):
    def __init__(self,saver_name,unit_to_saver_pipe,DB_conn):
        threading.Thread.__init__(self, name=saver_name)
        self.unit_to_saver_pipe = unit_to_saver_pipe
        self._DB_conn=DB_conn
    def run(self):
        while True:
            pipe_is_empty=self.unit_to_saver_pipe.empty()
            if pipe_is_empty is True:
                print("######Thread %s is empty ,break!"%self.getName())
                break
            req=self.unit_to_saver_pipe.get()
            print("######Thread %s START a job,processed Req: %d" % (self.getName(), req._id))
            self.working(req)
            print("######Thread %s FINISHED a job to processed Req: %d" % (self.getName(),req._id))
        print("######Thread %s exit" % self.getName())
    def working(self,req):
        DB_conn=self._DB_conn
        if (type(req) is not Req):
            raise Exception
        data_info_list=req.data_info.values()

        for data_info in data_info_list:
            try:
                if data_info["dataset_usage"] =="dataset_to_saver":
                    coll=DB_conn.get_coll(collname=data_info["coll_name"])
                    field_filter_list=data_info["field_filter_list"]
                    field_update_list=data_info["field_update_list"]
                    data_list_name=data_info["data_list_name"]
                    for doc in data_info[data_list_name]:
                        doc_filter={}
                        for field in field_filter_list:
                            doc_filter[field]=doc[field]
                        DB_conn.update_doc(coll=coll,doc_filter=doc_filter,new_doc=doc,field_update_list=field_update_list)
            except:
                print("ERROR",data_info)
                exit(1)
if __name__ == '__main__':
    myReq_list = []
    for i in range(5):
        input_info = {}
        input_info["unit_name"] = "SampleJudge"
        input_info["dataset_from_commit"] = {}
        input_info["dataset_from_commit"]["dataset_usage"] = "dataset_from_commit"
        input_info["dataset_from_commit"]["field_name_list"] = ['uid', 'pid', 'tid', 'ans']
        input_info["dataset_from_commit"]["uid_pid_tid_ans_list"] = []
        for j in range(10):
            input_info["dataset_from_commit"]["uid_pid_tid_ans_list"].append(Util.getDict(
                uid=i + 1, pid=100000001 + j // 4, tid=j % 4 + 1, ans=random.choice([-1, 0, 1]), ase=0))
        print(input_info)
        req = Req(id=i + 1, input_info=input_info)
        myReq_list.append(req)

    user_to_fetcher_pipe = Pipe()
    myReqFactory = ReqFactory("myReqFactory", user_to_fetcher_pipe)
    for r in myReq_list:
        myReqFactory.work(r)
    for r in myReq_list:
        print(r.fetch_info)

    myconn = MongoDBBase()

    fetcher_to_unit_pipe = Pipe()
    myFetcher1 = Fetcher("myFetcher1", user_to_fetcher_pipe=user_to_fetcher_pipe,
                         fetcher_to_unit_pipe=fetcher_to_unit_pipe, DB_conn=myconn)
    myFetcher1.start()
    myFetcher1.join()
    '''
       len=fetcher_to_unit_pipe.get_size()
    idx=0
    while idx<len:
        req=fetcher_to_unit_pipe.get()
        print("------")
        print(req.data_info)
        print("------")
        print("######Now fetcher_to_unit_pipe has %d req left"%fetcher_to_unit_pipe.get_size())
        idx+=1

    '''

    unit_to_saver_pipe = Pipe()
    myUnitFactory = UnitFactory("myUnit1", fetcher_to_unit_pipe=fetcher_to_unit_pipe,
                                unit_to_saver_pipe=unit_to_saver_pipe)
    myUnitFactory.start()
    myUnitFactory.join()
    '''
        len = unit_to_saver_pipe.get_size()
    idx = 0
    while idx < len:
        req = unit_to_saver_pipe.get()
        print("------")
        print(req.data_info)
        print("------")
        print("######Now unit_to_saver_pipe has %d req left" % unit_to_saver_pipe.get_size())
        idx += 1

    '''
    mySaver=Saver("mySaver1",unit_to_saver_pipe=unit_to_saver_pipe,DB_conn=myconn)
    mySaver.start()
    mySaver.join()